package com.template.controller;

import com.template.common.annotation.Authority;
import com.template.common.lang.R;
import com.template.common.validgroup.Create;
import com.template.common.validgroup.Update;
import com.template.domain.param.RoleParams;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.template.domain.entity.SysRole;
import com.template.service.SysRoleService;

import java.util.List;
import java.util.Set;

/**
 * 控制层。
 *
 * @author dong
 * @since 2023-09-03
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
public class SysRoleController {

    private final SysRoleService sysRoleService;

    @Authority("sys:role:get")
    @GetMapping("/list")
    public R<List<SysRole>> getList() {
        List<SysRole> list = sysRoleService.list();
        return R.success(list);
    }

    @Authority("sys:role:add")
    @PostMapping
    public R<String> add(@Validated(Create.class) @RequestBody SysRole sysRole) {
        sysRoleService.save(sysRole);
        return R.success();
    }

    @Authority("sys:role:update")
    @PutMapping
    public R<String> update(@Validated(Update.class) @RequestBody SysRole sysRole) {
        sysRoleService.updateById(sysRole);
        return R.success();
    }

    @Authority("sys:role:remove")
    @DeleteMapping
    public R<String> delete(@NotNull(message = "角色id为必要参数") Long id) {
        sysRoleService.removeById(id);
        return R.success();
    }

    /**
     * 获取角色权限码的id
     */
    @GetMapping("/perms")
    public R<Set<Long>> getPermsById(Long id) {
        Set<Long> userPerms = sysRoleService.getRolePermsId(id);
        return R.success(userPerms);
    }

    /**
     * 分配角色权限
     */
    @Authority("sys:role:assign")
    @PostMapping("/assign-perms")
    public R<String> assignPerms(@Validated @RequestBody RoleParams.AssignPerms assignPerms) {
        log.info("{}", assignPerms);
        sysRoleService.assignPerms(assignPerms.getRoleId(), assignPerms.getPermsIds());
        return R.success();
    }
}
